package com.crossriver.crgis.portlet;

import java.io.IOException;
import java.util.Enumeration;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.crossriver.crgis.cofo.util.ApplicationActionUtil;
import com.crossriver.crgis.cofo.util.ApplicationCofOConstants;
import com.crossriver.crgis.cofo.util.CofORetrieveUtil;
import com.crossriver.crgis.database.model.Application_C_of_O;
import com.crossriver.crgis.database.service.Application_C_of_OLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;

/**
 * Portlet implementation class Requests
 */
public class Requests extends MVCPortlet {
	
	private static Log log = LogFactory.getLog(Requests.class);

	
	public void viewApplicationDetail(ActionRequest actionRequest, 
				ActionResponse actionResponse){
		


		if (log.isInfoEnabled()){
		log.info("In  viewApplicationDetail" );
		}
		Application_C_of_O appCofO = ApplicationActionUtil.
						getApplication_C_of_OFromRequest(actionRequest);

		if (log.isInfoEnabled()){
			log.info("successfully retrieved  AttestationInformation from the web >>> " 
				+ appCofO.toString() +"<<< " + appCofO.getApplicationId()  );}
		

		Application_C_of_O appCofOTemp = appCofO;
		try {
			if (log.isInfoEnabled()){
			log.info("successfully retrieved AttestationInformation for update >>> " 
					+ appCofO.toString() +"<<< " + appCofO.getApplicationId()  );}
			appCofOTemp = Application_C_of_OLocalServiceUtil.
					getApplication_C_of_O(appCofO.getApplicationId());
			
			appCofOTemp.setAttestation(appCofO.getAttestation());
			
			Application_C_of_OLocalServiceUtil.
				updateApplication_C_of_O(appCofOTemp);
			if (log.isInfoEnabled()){
			log.info("successfully saved  AttestationInformation  >>> " 
					+ appCofO.toString() +"<<< " + appCofO.getApplicationId()  );}
			

			
		} catch (PortalException e) {
			if (log.isDebugEnabled()){
			log.debug("Updating Application >>" + appCofOTemp.toString() + " <<< failed");
			log.debug("There is a problem persisting Application information " +e.getMessage());
			}
			//do a page for application error.
			actionRequest.setAttribute("jspPage", "/html/application_cofo/ApplicationError.jsp");
	        actionResponse.setRenderParameter("jspPage", "/html/application_cofo/ApplicationError.jsp");

			
			SessionErrors.add(actionRequest, "application-error");
			e.printStackTrace();
			return;
		} catch (SystemException e) {
			if (log.isDebugEnabled()){
			log.debug("Updating Application >>" + appCofOTemp.toString() + " <<< failed");
			log.debug("There is a problem persisting Application information " +e.getMessage());
			}
			//do a page for application error.
			actionRequest.setAttribute("jspPage", "/html/application_cofo/ApplicationError.jsp");
	        actionResponse.setRenderParameter("jspPage", "/html/application_cofo/ApplicationError.jsp");

			
			SessionErrors.add(actionRequest, "application-error");
			e.printStackTrace();
			return;
		}
		
		
		//TODO
		//retrieve all the information that has been saved and put them on the 
		//request scope.
		//assume that their is failure
		actionRequest.setAttribute("jspPage", "/html/application_cofo/ApplicationError.jsp");
        actionResponse.setRenderParameter("jspPage", "/html/application_cofo/ApplicationError.jsp");
		SessionErrors.add(actionRequest, "application-error");

		String applicationType = appCofOTemp.getApplicationType();
		
		//check application
		boolean retreiveInformation = 
			CofORetrieveUtil.extractApplicationInfoForDisplay(actionRequest,  appCofOTemp);
		
		
		
		//test personal info
		if(applicationType.equalsIgnoreCase(ApplicationCofOConstants.APPLICATION_TYPE_INDIVIDUAL)){
			if( retreiveInformation){
				retreiveInformation = CofORetrieveUtil.extractPersonalInfoForDisplay(actionRequest,  appCofOTemp);
			}else{
				return;
			}	
		}
		
		//do company information
		if(applicationType.equalsIgnoreCase(ApplicationCofOConstants.APPLICATION_TYPE_ORGANISATION)){
			if( retreiveInformation){
				retreiveInformation = CofORetrieveUtil.extractOrganisationInfoForDisplay(actionRequest,  appCofOTemp);
			}else{
				return;
			}	
		}
		
		//do company contact
		if(applicationType.equalsIgnoreCase(ApplicationCofOConstants.APPLICATION_TYPE_ORGANISATION)){
			if( retreiveInformation){
				retreiveInformation = CofORetrieveUtil.extractCompanyContactInfoForDisplay(actionRequest,  appCofOTemp);
			}else{
				return;
			}	
		}
		
		
		//test contact info
		if( retreiveInformation){
			retreiveInformation = CofORetrieveUtil.extractContactInfoForDisplay(actionRequest,  appCofOTemp);
		}else{
			return;
		}
		
		//application history
		if( retreiveInformation){
			retreiveInformation = CofORetrieveUtil.extractApplicationHistForDisplay(actionRequest,  appCofOTemp);
		}else{
			return;
		}
		
		//test property info
		if( retreiveInformation){
			retreiveInformation = CofORetrieveUtil.extractPropertyInfoForDisplay(actionRequest,  appCofOTemp);
		}else{
			return;
		}
		
		//test supporting docs
		if( retreiveInformation){
			retreiveInformation = 
				CofORetrieveUtil.extractSupportDocForDisplay(actionRequest,  appCofOTemp);
		}else{
			return;
		}
		
		
		log.info("Successfully all the information for display >>> " +appCofOTemp.getApplicationId() );
		

		String applicationCompleteJSP = "";
		if (applicationType
				.equalsIgnoreCase(ApplicationCofOConstants.APPLICATION_TYPE_INDIVIDUAL)) {
			applicationCompleteJSP = "/html/application_cofo/individual/ApplicationCofOIndComplete.jsp";
		} else {
			applicationCompleteJSP = "/html/application_cofo/organisation/ApplicationCofOOrgComplete.jsp";
		}
		
		actionRequest.setAttribute("jspPage", applicationCompleteJSP);
		actionResponse.setRenderParameter("jspPage", applicationCompleteJSP);
		
	
	}
 

	/**
	 * This method can be evoked before the final save method is called. 
	 * For application, when reuest for delete comes, we are not removing the 
	 * application data from the database. We will tag the application as deleted.
	 * 
	 * 
	 * We are adopting this so that we can analyse requests that are deleted.
	 * Abuse of the system can also be traced with this.
	 * 
	 * One request is tagged as deleted, we exclude it from being seen again
	 * user. How ever the back end users will still be able to see this.
	 * 
	 * 
	 * @param actionRequest
	 * @param actionResponse
	 */

	public void deleteApplication(ActionRequest actionRequest,
			ActionResponse actionResponse) {


		Application_C_of_O appCofO = ApplicationActionUtil
				.getApplication_C_of_OFromRequest(actionRequest);

		// this is retrieved for use in later stage
		Application_C_of_O application = null;
		try {
			application = Application_C_of_OLocalServiceUtil
					.getApplication_C_of_O(appCofO.getApplicationId());

		

			application
					.setStatus(ApplicationCofOConstants.APPL_C_OF_O_STATUS_DELETED);
			boolean merge = true;
			Application_C_of_OLocalServiceUtil.updateApplication_C_of_O(
					application, merge);

		} catch (PortalException e) {
			if (log.isErrorEnabled()) {
				log.debug("Creating Application >>" + application.toString()
						+ " <<< failed");
				log.debug("There is a problem persisting Application information "
						+ e.getMessage());
			}
			// do a page for application error.
			actionRequest.setAttribute("jspPage",
					"/html/application_cofo/ApplicationError.jsp");
			actionResponse.setRenderParameter("jspPage",
					"/html/application_cofo/ApplicationError.jsp");

			SessionErrors.add(actionRequest, "application-error");
			e.printStackTrace();
			return;
		} catch (SystemException e) {
			if (log.isDebugEnabled()) {
				log.debug("Creating Application >>" + application.toString()
						+ " <<< failed");
				log.debug("There is a problem persisting Application information "
						+ e.getMessage());
			}
			// do a page for application error.
			actionRequest.setAttribute("jspPage",
					"/html/application_cofo/ApplicationError.jsp");
			actionResponse.setRenderParameter("jspPage",
					"/html/application_cofo/ApplicationError.jsp");

			SessionErrors.add(actionRequest, "application-error");
			e.printStackTrace();
			return;
		}

		// TODO
		// update Application_C_of_O and proceed to the next stage

		// if the attestation is not done, display an error message

		SessionMessages.add(actionRequest, "application-successfully-deleted");
		
		actionRequest.setAttribute(
				ApplicationCofOConstants.APPL_C_OF_O_SESSION_ATTR, application);

		actionRequest.setAttribute("jspPage",
				"/html/requests/view.jsp");
		actionResponse.setRenderParameter("jspPage",
				"/html/requests/view.jsp");

	}
	
	@Override
	public void doView(RenderRequest renderRequest,
			RenderResponse renderResponse) throws IOException, PortletException {

		log.info("In method doView()");
		
		HttpServletRequest request = PortalUtil
		.getHttpServletRequest(renderRequest);
		
		HttpServletRequest origRequest = PortalUtil
		.getOriginalServletRequest(request);
		
		Enumeration params = origRequest.getParameterNames();
		
		String __show_delete = origRequest.getParameter("__show-delete-message");
		if("YES".equalsIgnoreCase(__show_delete)){
			SessionMessages.add(renderRequest, "application-successfully-deleted");
		}
		

		super.doView(renderRequest, renderResponse);
		
//		while (params.hasMoreElements()){
//			String elt = (String)params.nextElement();
//			System.out.println(elt + "=" +origRequest.getParameter((String)elt) );
//		}
		

	}

}
